import type {
  IPagination,
  IPost,
  ISection,
  ITag,
  ITagStatistics,
} from '@/interfaces';
import type { TBody, TParams } from '@/types';
import { createConfig, getQueryParams, handleReqMiddleware } from '@/lib/api';

export const queryTagStatistics = (
  params?: TParams
): Promise<Response | ITagStatistics> => {
  const config = createConfig(params);
  return fetch(config.baseURL + '/forum/tags/statistics', config).then(
    handleReqMiddleware
  );
};

export const createTag = (
  params: TBody<{
    name: string;
  }>
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'POST' });
  return fetch(config.baseURL + '/forum/tags', config).then(
    handleReqMiddleware
  );
};

export const queryAllTag = (
  params?: TParams
): Promise<Response | IPagination<ITag>> => {
  const config = createConfig(params);
  return fetch(
    config.baseURL + `/forum/tags?${getQueryParams(config)}`,
    config
  ).then(handleReqMiddleware);
};

export const queryTagDetails = (params?: TParams): Promise<Response | ITag> => {
  const config = createConfig(params);
  return fetch(
    config.baseURL + `/forum/tags/${config.id}/details`,
    config
  ).then(handleReqMiddleware);
};

export const queryTagSections = (
  params?: TParams
): Promise<Response | IPagination<ISection>> => {
  const config = createConfig(params);
  return fetch(
    config.baseURL + `/forum/tags/${config.id}/sections`,
    config
  ).then(handleReqMiddleware);
};

export const queryTagPosts = (
  params?: TParams
): Promise<Response | IPagination<IPost>> => {
  const config = createConfig(params);
  return fetch(config.baseURL + `/forum/tags/${config.id}/posts`, config).then(
    handleReqMiddleware
  );
};

export const updateTag = (
  params: TBody<{
    name: string;
  }>
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'PUT' });
  return fetch(config.baseURL + `/forum/tags/${config.id}`, config).then(
    handleReqMiddleware
  );
};

export const removeTag = (params: TBody<void>): Promise<Response | boolean> => {
  const config = createConfig(params, { method: 'DELETE' });
  return fetch(config.baseURL + `/forum/tags/${config.id}`, config).then(
    handleReqMiddleware
  );
};
